﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace SaturniLibrary.Toolkit
{
    public partial class Main : Form
    {
        FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
        const int chunkSize = 2 * 1024;
        const int BufferSize = 8096;

        public Main()
        {
            InitializeComponent();
        }

        private void btnMerge_Click(object sender, EventArgs e)
        {
            string folderPath = tbFolder.Text.Trim();
            if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath))
            {
                MessageBox.Show("文件夹路径不存在！");
                return;
            }
            string[] files = Directory.GetFiles(folderPath, "*.sql", SearchOption.AllDirectories);
            string outputFullFileName = SaturniLibrary.IO.FileName.GenerateFileName(folderPath, "merge-output", "sql");
            FileStream outPutFileStream = new FileStream(outputFullFileName, FileMode.OpenOrCreate, FileAccess.Write);           
            using (TextWriter twOutput = new StreamWriter(outPutFileStream, Encoding.UTF8))
            {
                foreach (string inputFileName in files)
                {
                    using (TextReader trInput = new StreamReader(inputFileName))
                    {
                        char[] buffer = new char[BufferSize];
                        int len;

                        while ((len = trInput.Read(buffer, 0, BufferSize)) > 0)
                        {
                            twOutput.Write(buffer, 0, len);
                        }
                        twOutput.Write("\r\n");
                    }
                }   
            }
            outPutFileStream.Close();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            DialogResult dr = folderBrowserDialog.ShowDialog();
            tbFolder.Text = folderBrowserDialog.SelectedPath;
        }
    }
}
